package com.example.a15787.weather_zyy_1235;

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.TransitionDrawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity {
    private TextView tvCity, tvTemperature, tvHumidity, tvPm25, tvWind;
    private RecyclerView rvForecast;
    private TextView tvTime;
    private Spinner citySpinner;
    private WeatherResponse weatherResponse;
    private List<String> cityNames = new ArrayList<String>();
    private LocationManager locationManager;
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    private static final int SHARE_WEATHER_CARD_REQUEST_CODE = 2;
    private TextView tvLocationStatus;
    private ImageView shareButton;
    private Timer timer;
    private android.support.design.widget.BottomNavigationView bottomNavigationView;
    private ImageView currentCityIcon;
    private boolean isNetworkConnected = false;
    private boolean hasCacheData = false;
    private boolean isDialogShown = false;
    private LinearLayout rootLayout; // 添加根布局引用
    private int currentBackgroundResId = -1; // 当前背景资源ID

    // 添加背景图片资源ID数组
    private static final int[] WEATHER_BACKGROUNDS = {
            R.drawable.bg_sunny,    // 晴天
            R.drawable.bg_cloudy,   // 多云
            R.drawable.bg,    // 雨天
            R.drawable.bg_snowy,    //
            R.drawable.bg,    // 雾天
            R.drawable.bg_default   // 默认背景
    };

    private static final String PREFS_NAME = "WeatherPrefs";
    private static final String KEY_WEATHER_DATA = "weather_data";
    private static final String KEY_TIMESTAMP = "timestamp";
    private static final long CACHE_VALIDITY = 60 * 60 * 1000;
    private WeatherDatabaseHelper dbHelper;

    private NetworkChangeReceiver networkChangeReceiver;

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    private void showNetworkErrorDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!isFinishing() && !isDestroyed() && !isDialogShown) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                    builder.setTitle("网络连接错误");
                    builder.setMessage("当前无网络连接，将使用缓存数据。请检查网络设置后重试。");
                    builder.setPositiveButton("确定", null);
                    builder.setOnDismissListener(new AlertDialog.OnDismissListener() {
                        @Override
                        public void onDismiss(android.content.DialogInterface dialogInterface) {
                            isDialogShown = false;
                        }
                    });
                    builder.show();
                    isDialogShown = true;
                }
            }
        });
    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivityManager != null) {
            NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
            return activeNetworkInfo != null && activeNetworkInfo.isConnected();
        }
        return false;
    }

    private boolean hasValidCache() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(
                WeatherDatabaseHelper.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                null
        );

        boolean cacheExists = false;
        if (cursor.moveToFirst()) {
            long timestamp = cursor.getLong(cursor.getColumnIndex(WeatherDatabaseHelper.COLUMN_TIMESTAMP));
            long currentTime = System.currentTimeMillis();

            if (currentTime - timestamp < CACHE_VALIDITY) {
                String cachedData = cursor.getString(cursor.getColumnIndex(WeatherDatabaseHelper.COLUMN_DATA));
                if (cachedData != null) {
                    cacheExists = true;
                }
            }
        }

        cursor.close();
        db.close();

        if (!cacheExists) {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long timestamp = prefs.getLong(KEY_TIMESTAMP, 0);
            long currentTime = System.currentTimeMillis();

            if (currentTime - timestamp < CACHE_VALIDITY) {
                String cachedData = prefs.getString(KEY_WEATHER_DATA, null);
                if (cachedData != null) {
                    cacheExists = true;
                }
            }
        }

        return cacheExists;
    }

    private boolean loadWeatherFromCache() {
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor = db.query(
                WeatherDatabaseHelper.TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                null
        );

        boolean cacheExists = false;
        if (cursor.moveToFirst()) {
            long timestamp = cursor.getLong(cursor.getColumnIndex(WeatherDatabaseHelper.COLUMN_TIMESTAMP));
            long currentTime = System.currentTimeMillis();

            if (currentTime - timestamp < CACHE_VALIDITY) {
                String cachedData = cursor.getString(cursor.getColumnIndex(WeatherDatabaseHelper.COLUMN_DATA));
                if (cachedData != null) {
                    try {
                        weatherResponse = WeatherParser.parse(cachedData);
                        setupCitySpinner();
                        updateWeatherUIForCity(0);
                        cacheExists = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        cursor.close();
        db.close();

        if (!cacheExists) {
            SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
            long timestamp = prefs.getLong(KEY_TIMESTAMP, 0);
            long currentTime = System.currentTimeMillis();

            if (currentTime - timestamp < CACHE_VALIDITY) {
                String cachedData = prefs.getString(KEY_WEATHER_DATA, null);
                if (cachedData != null) {
                    try {
                        weatherResponse = WeatherParser.parse(cachedData);
                        setupCitySpinner();
                        updateWeatherUIForCity(0);
                        cacheExists = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        hasCacheData = cacheExists;
        return cacheExists;
    }

    public String url = "http://192.168.0.108:8080/weather-api/new_weather_data.json";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        dbHelper = new WeatherDatabaseHelper(this);

        // 初始化根布局
        rootLayout = (LinearLayout) findViewById(R.id.root_layout);

        // 设置初始背景
        currentBackgroundResId = WEATHER_BACKGROUNDS[5];
        rootLayout.setBackgroundResource(currentBackgroundResId);

        setupViews();

        networkChangeReceiver = new NetworkChangeReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(networkChangeReceiver, filter);

        updateNetworkStatus();
        hasCacheData = hasValidCache();

        if (!isNetworkConnected && hasCacheData) {
            loadWeatherFromCache();
            showNetworkErrorDialog();
        } else {
            loadWeatherData();
        }

        checkLocationPermission();
        setupShareButton();
        startUpdatingTime();
        setupBottomNavigation();
        showFragment(new WeatherFragment());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {
        if (intent != null) {
            if (intent.hasExtra("SELECTED_CITY")) {
                String selectedCity = intent.getStringExtra("SELECTED_CITY");
                if (cityNames != null && cityNames.contains(selectedCity)) {
                    int cityPosition = cityNames.indexOf(selectedCity);
                    citySpinner.setSelection(cityPosition);
                    updateWeatherUIForCity(cityPosition);
                }
            }

            if (intent.getBooleanExtra("SELECT_WEATHER_TAB", false)) {
                bottomNavigationView.setSelectedItemId(R.id.nav_weather);
            }
        }
    }

    private void updateNetworkStatus() {
        isNetworkConnected = isNetworkAvailable();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }

        if (networkChangeReceiver != null) {
            unregisterReceiver(networkChangeReceiver);
        }
    }

    private class NetworkChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            boolean oldNetworkState = isNetworkConnected;
            updateNetworkStatus();
            hasCacheData = hasValidCache();

            if (!isNetworkConnected && hasCacheData && !oldNetworkState) {
                loadWeatherFromCache();
                showNetworkErrorDialog();
            } else if (isNetworkConnected && !oldNetworkState) {
                loadWeatherData();
            }
        }
    }

    private void setupViews() {
        tvCity = (TextView) findViewById(R.id.tvCity);
        tvHumidity = (TextView) findViewById(R.id.tvHumidity);
        tvPm25 = (TextView) findViewById(R.id.tvPm25);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvWind = (TextView) findViewById(R.id.tvWind);
        tvTemperature = (TextView) findViewById(R.id.tvTemperature);
        rvForecast = (RecyclerView) findViewById(R.id.rvForecast);
        LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
        rvForecast.setLayoutManager(layoutManager);
        citySpinner = (Spinner) findViewById(R.id.citySpinner);
        citySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                updateWeatherUIForCity(position);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
        tvLocationStatus = (TextView) findViewById(R.id.tvLocationStatus);
        shareButton = (ImageView) findViewById(R.id.shareButton);
        bottomNavigationView = (android.support.design.widget.BottomNavigationView) findViewById(R.id.bottom_navigation);
        currentCityIcon = (ImageView) findViewById(R.id.imageButton);
    }

    private void loadWeatherData() {
        updateNetworkStatus();
        hasCacheData = hasValidCache();

        if (!isNetworkConnected && hasCacheData) {
            loadWeatherFromCache();
            showNetworkErrorDialog();
            return;
        }

        if (isNetworkConnected) {
            new WeatherTask().execute(url);
        } else {
            showToast("无法获取天气数据，请检查网络连接");
        }
    }

    private class WeatherTask extends AsyncTask<String, Void, WeatherResponse> {
        @Override
        protected WeatherResponse doInBackground(String... urls) {
            try {
                String jsonResponse = NetworkUtils.fetchWeatherData(urls[0]);
                return WeatherParser.parse(jsonResponse);
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

        @Override
        protected void onPostExecute(WeatherResponse result) {
            if (result != null) {
                weatherResponse = result;
                setupCitySpinner();

                Intent intent = getIntent();
                if (intent != null && intent.hasExtra("SELECTED_CITY")) {
                    String selectedCity = intent.getStringExtra("SELECTED_CITY");
                    if (cityNames.contains(selectedCity)) {
                        int cityPosition = cityNames.indexOf(selectedCity);
                        citySpinner.setSelection(cityPosition);
                        updateWeatherUIForCity(cityPosition);
                    }
                } else {
                    updateWeatherUIForCity(0);
                }

                SQLiteDatabase db = dbHelper.getWritableDatabase();
                db.delete(WeatherDatabaseHelper.TABLE_NAME, null, null);

                ContentValues values = new ContentValues();
                values.put(WeatherDatabaseHelper.COLUMN_DATA, result.toString());
                values.put(WeatherDatabaseHelper.COLUMN_TIMESTAMP, System.currentTimeMillis());
                db.insert(WeatherDatabaseHelper.TABLE_NAME, null, values);
                db.close();

                SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = prefs.edit();
                editor.putString(KEY_WEATHER_DATA, result.toString());
                editor.putLong(KEY_TIMESTAMP, System.currentTimeMillis());
                editor.apply();

                hasCacheData = true;
            } else {
                SharedPreferences prefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
                String cachedData = prefs.getString(KEY_WEATHER_DATA, null);

                if (cachedData != null) {
                    showNetworkErrorDialog();
                    try {
                        weatherResponse = WeatherParser.parse(cachedData);
                        setupCitySpinner();
                        updateWeatherUIForCity(0);
                        hasCacheData = true;
                    } catch (Exception e) {
                        e.printStackTrace();
                        showToast("无法获取天气数据，请检查网络连接");
                        hasCacheData = false;
                    }
                } else {
                    showToast("无法获取天气数据，请检查网络连接");
                    hasCacheData = false;
                }
            }
        }
    }

    private void setupCitySpinner() {
        cityNames.clear();
        for (WeatherResponse.City city : weatherResponse.cities) {
            cityNames.add(city.getCityName());
        }
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, cityNames);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        citySpinner.setAdapter(adapter);
    }

    private void updateWeatherUIForCity(int position) {
        WeatherResponse.City city = weatherResponse.cities.get(position);
        tvCity.setText("当前城市：" + city.getCityName());
        List<WeatherResponse.Forecast> forecasts = city.getWeatherForecast();
        if (!forecasts.isEmpty()) {
            WeatherResponse.Forecast firstForecast = forecasts.get(0);
            tvTemperature.setText("当前温度：" + firstForecast.getTemperature().getMin() + " ~ " + firstForecast.getTemperature().getMax() + "℃");
            tvHumidity.setText("湿度：" + firstForecast.getHumidity() + "%");
            tvPm25.setText("PM2.5：" + String.format("%.1f", firstForecast.getPm25()));
            tvWind.setText("风速：" + firstForecast.getWind());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
            String currentTime = sdf.format(new Date());
            tvTime.setText("当前时间：" + currentTime);

            int iconResId = ForecastAdapter.getIconResource(firstForecast.getIcon());
            currentCityIcon.setImageResource(iconResId);

            // 根据天气类型设置背景
            setWeatherBackground(firstForecast.getWeather());

            showWeatherTips(firstForecast.getWeather());
        }
        rvForecast.setAdapter(new ForecastAdapter(forecasts));
    }

    // 根据天气类型设置背景（带平滑过渡动画）
    private void setWeatherBackground(String weatherType) {
        int newBgResource = WEATHER_BACKGROUNDS[5]; // 默认为默认背景

        // 根据天气类型选择背景
        if (weatherType.contains("多云转晴") || weatherType.contains("晴转多云")) {
            newBgResource = WEATHER_BACKGROUNDS[1]; // 使用多云背景
        } else if (weatherType.contains("晴")) {
            newBgResource = WEATHER_BACKGROUNDS[0]; // 晴天背景
        } else if (weatherType.contains("多云")) {
            newBgResource = WEATHER_BACKGROUNDS[1]; // 多云背景
        } else if (weatherType.contains("雨")) {
            newBgResource = WEATHER_BACKGROUNDS[2]; // 雨天背景
        } else if (weatherType.contains("雷阵雨")) {
            newBgResource = WEATHER_BACKGROUNDS[3]; // 雪天背景
        } else if (weatherType.contains("雾")) {
            newBgResource = WEATHER_BACKGROUNDS[4]; // 雾天背景
        }

        // 如果背景相同，则不执行动画
        if (currentBackgroundResId == newBgResource) {
            return;
        }

        // 创建平滑过渡动画
        if (rootLayout != null) {
            // 获取当前背景和新的背景
            Drawable currentDrawable = ContextCompat.getDrawable(this, currentBackgroundResId);
            Drawable newDrawable = ContextCompat.getDrawable(this, newBgResource);

            if (currentDrawable != null && newDrawable != null) {
                // 创建TransitionDrawable（包含两个Drawable的数组）
                TransitionDrawable transitionDrawable = new TransitionDrawable(new Drawable[]{
                        currentDrawable,
                        newDrawable
                });

                // 设置背景为TransitionDrawable
                rootLayout.setBackground(transitionDrawable);

                // 开始过渡动画（500毫秒的淡入淡出效果）
                transitionDrawable.startTransition(500);
            } else {
                // 如果无法获取Drawable，直接设置背景
                rootLayout.setBackgroundResource(newBgResource);
            }
        } else {
            Log.e("Background", "Root layout is null, cannot set background");
        }

        // 更新当前背景资源ID
        currentBackgroundResId = newBgResource;
    }

    private void showWeatherTips(String weatherType) {
        String tips = "愿你今天像太阳一样心情灿烂";
        int iconResId = R.drawable.ic_default; // 默认提示图标

        String[] weatherParts = weatherType.split("转");
        for (String part : weatherParts) {
            if (part.contains("多云") || part.contains("cloudy")) {
                tips = "多云的天气适合出行，记得带上好心情哦！";
                iconResId = R.drawable.ic_cloudy;
                break;
            } else if (part.contains("晴") || part.contains("sunny")) {
                tips = "阳光明媚的日子，愿你心情如阳光般灿烂！";
                iconResId = R.drawable.ic_sunny;
                break;
            } else if (part.contains("雷阵雨") || part.contains("thunder")) {
                tips = "雷雨天气请注意安全，记得关闭门窗哦！";
                iconResId = R.drawable.ic_rainy;
                break;
            } else if (part.contains("雨") || part.contains("rain")) {
                tips = "雨天路滑，记得带伞，愿雨水洗去所有烦恼~";
                iconResId = R.drawable.light_rain;
                break;
            } else if (part.contains("风")) {
                tips = "刮风的日子，记得添加衣物，别着凉啦~";
                iconResId = R.drawable.ic_default;
                break;
            } else if (part.contains("雪")) {
                tips = "下雪天注意保暖，小心路滑~";
                iconResId = R.drawable.ic_default;
                break;
            } else if (part.contains("雾")) {
                tips = "雾天能见度低，出行请注意安全~";
                iconResId = R.drawable.ic_default;
                break;
            }
        }

        // 创建自定义带图标的提示
        showToastWithIcon(tips, iconResId);
    }

    // 显示带图标的提示
    private void showToastWithIcon(String message, int iconResId) {
        // 创建自定义布局
        View layout = getLayoutInflater().inflate(R.layout.custom_toast,
                (ViewGroup) findViewById(R.id.toast_layout_root));

        // 设置图标
        ImageView icon = layout.findViewById(R.id.toast_icon);
        icon.setImageResource(iconResId);

        // 设置文本
        TextView text = layout.findViewById(R.id.toast_text);
        text.setText(message);

        // 创建并显示Toast
        Toast toast = new Toast(getApplicationContext());
        toast.setDuration(Toast.LENGTH_LONG);
        toast.setView(layout);

        // 设置位置（屏幕底部中央）
        toast.setGravity(Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 100);
        toast.show();
    }

    private void checkLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED ||
                ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION},
                    LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            tvLocationStatus.setText("正在定位...");
            startLocationUpdates();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 &&
                    (grantResults[0] == PackageManager.PERMISSION_GRANTED || grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                tvLocationStatus.setText("正在定位...");
                startLocationUpdates();
            } else {
                showToast("定位权限被拒绝");
            }
        }
    }

    private void startLocationUpdates() {
        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (isGPSEnabled) {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        } else if (isNetworkEnabled) {
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
        } else {
            showToast("无法获取定位信息，请检查GPS或网络设置");
        }
    }

    private final LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            String cityName = getCityNameFromLocation(location);
            int cityPosition = getCityPosition(cityName);
            if (cityPosition != -1) {
                citySpinner.setSelection(cityPosition);
                tvLocationStatus.setText("定位成功");
            }
            locationManager.removeUpdates(this);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }
    };

    private String getCityNameFromLocation(Location location) {
        return "福州";
    }

    private int getCityPosition(String cityName) {
        for (int i = 0; i < cityNames.size(); i++) {
            if (cityNames.get(i).equals(cityName)) {
                return i;
            }
        }
        return -1;
    }

    private void setupShareButton() {
        shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShareOptions();
            }
        });
    }

    private void showShareOptions() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("分享天气信息");
        builder.setItems(new String[]{"分享文本", "分享天气卡片"}, new android.content.DialogInterface.OnClickListener() {
            @Override
            public void onClick(android.content.DialogInterface dialog, int which) {
                if (which == 0) {
                    shareWeatherInfo();
                } else {
                    shareWeatherCard();
                }
            }
        });
        builder.show();
    }

    private void shareWeatherInfo() {
        String city = tvCity.getText().toString();
        String temperature = tvTemperature.getText().toString();
        String humidity = tvHumidity.getText().toString();
        String pm25 = tvPm25.getText().toString();
        String wind = tvWind.getText().toString();
        String time = tvTime.getText().toString();
        String shareText = city + "\n" + temperature + "\n" + humidity + "\n" + pm25 + "\n" + wind + "\n" + time;
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, shareText);
        if (shareIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(Intent.createChooser(shareIntent, "分享天气信息"), SHARE_WEATHER_CARD_REQUEST_CODE);
        }
    }

    private void shareWeatherCard() {
        // 创建天气卡片Bitmap
        Bitmap weatherCard = createWeatherCardBitmap();

        // 保存图片到本地
        File imageFile = saveBitmapToFile(weatherCard);
        if (imageFile != null) {
            // 分享图片
            Intent shareIntent = new Intent(Intent.ACTION_SEND);
            shareIntent.setType("image/*");
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(imageFile));
            shareIntent.putExtra(Intent.EXTRA_TEXT, "分享天气卡片");
            if (shareIntent.resolveActivity(getPackageManager()) != null) {
                startActivityForResult(Intent.createChooser(shareIntent, "分享天气卡片"), SHARE_WEATHER_CARD_REQUEST_CODE);
            }
        } else {
            showToast("创建天气卡片失败");
        }
    }

    private Bitmap createWeatherCardBitmap() {
        // 获取当前天气数据
        int position = citySpinner.getSelectedItemPosition();
        WeatherResponse.City city = weatherResponse.cities.get(position);
        WeatherResponse.Forecast forecast = city.getWeatherForecast().get(0);

        // 创建Bitmap
        int width = 800;
        int height = 1000;
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);

        // 绘制背景
        Paint backgroundPaint = new Paint();
        backgroundPaint.setColor(Color.parseColor("#2196F3"));
        canvas.drawRect(0, 0, width, height, backgroundPaint);

        // 绘制城市名称
        Paint textPaint = new Paint();
        textPaint.setColor(Color.WHITE);
        textPaint.setTextSize(48);
        textPaint.setTypeface(Typeface.DEFAULT_BOLD);
        textPaint.setAntiAlias(true);

        float cityTextWidth = textPaint.measureText(city.getCityName());
        canvas.drawText(city.getCityName(), (width - cityTextWidth) / 2, 100, textPaint);

        // 绘制天气图标
        Drawable weatherIcon = getResources().getDrawable(ForecastAdapter.getIconResource(forecast.getIcon()));
        weatherIcon.setBounds(width / 2 - 100, 150, width / 2 + 100, 350);
        weatherIcon.draw(canvas);

        // 绘制温度
        textPaint.setTextSize(60);
        String tempText = forecast.getTemperature().getMin() + " ~ " + forecast.getTemperature().getMax() + "℃";
        float tempTextWidth = textPaint.measureText(tempText);
        canvas.drawText(tempText, (width - tempTextWidth) / 2, 450, textPaint);

        // 绘制天气状态
        textPaint.setTextSize(36);
        float weatherTextWidth = textPaint.measureText(forecast.getWeather());
        canvas.drawText(forecast.getWeather(), (width - weatherTextWidth) / 2, 500, textPaint);

        // 绘制其他信息
        textPaint.setTextSize(28);
        String humidityText = "湿度: " + forecast.getHumidity() + "%";
        String pm25Text = "PM2.5: " + String.format("%.1f", forecast.getPm25());
        String windText = "风速: " + forecast.getWind();

        canvas.drawText(humidityText, 100, 600, textPaint);
        canvas.drawText(pm25Text, 100, 650, textPaint);
        canvas.drawText(windText, 100, 700, textPaint);

        // 绘制时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.getDefault());
        String timeText = "更新时间: " + sdf.format(new Date());
        canvas.drawText(timeText, 100, 750, textPaint);

        return bitmap;
    }

    private File saveBitmapToFile(Bitmap bitmap) {
        File imagesFolder = new File(Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES), "WeatherCards");
        if (!imagesFolder.exists()) {
            imagesFolder.mkdirs();
        }

        String fileName = "weather_" + System.currentTimeMillis() + ".jpg";
        File imageFile = new File(imagesFolder, fileName);

        try {
            FileOutputStream outputStream = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream);
            outputStream.flush();
            outputStream.close();
            return imageFile;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == SHARE_WEATHER_CARD_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                // 解析分享结果的包名（仅当data不为空时）
                String packageName = data != null && data.getData() != null
                        ? data.getData().getSchemeSpecificPart()
                        : "";

                // 判断是否为微信分享成功
                if (packageName.contains("wechat") || packageName.contains("com.tencent.mm")) {
                    showToast("已成功分享到微信");
                } else if (packageName.contains("qq") || packageName.contains("com.tencent.mobileqq")) {
                    showToast("已成功分享到QQ");
                } else {
                    showToast("分享成功");
                }
            } else if (resultCode == RESULT_CANCELED) {
                showToast("分享成功");
            }
        }
    }

    private void startUpdatingTime() {
        timer = new Timer();
        timer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String currentTime = sdf.format(new Date());
                        tvTime.setText("当前时间：" + currentTime);
                    }
                });
            }
        }, 0, 1000);
    }

    private void setupBottomNavigation() {
        bottomNavigationView.setOnNavigationItemSelectedListener(new android.support.design.widget.BottomNavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(@NonNull MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.nav_weather:
                        showFragment(new WeatherFragment());
                        return true;
                    case R.id.nav_city:
                        Intent intent = new Intent(MainActivity.this, CitySearchActivity.class);
                        startActivity(intent);
                        return true;
                }
                return false;
            }
        });
    }

    private void showFragment(Fragment fragment) {
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        transaction.replace(R.id.fragment_container, fragment);
        transaction.commit();
    }
}